<template>
	<div>
		<Row>
			<Col span="4">
			<Tree :data="areaList" class="tree-data-container" @on-select-change="onSelectChange" />
			</Col>
			<Col span="20">
			<Button type="primary" :disabled="selectedArea.nodeLevel !== 4 || !selectedAlarms.length"
				style="margin-right: 10px;" @click="onShowBatchConfirm">确认</Button>
			<Button type="error" :disabled="selectedArea.nodeLevel !== 4 || !selectedAlarms.length"
				style="margin-right: 10px;" @click="onDelete">删除</Button>
			<Button type="info" @click="onExport">导出</Button>
			<div class="ivu-inline-block ivu-fr">
				<Dropdown @on-click="onChangeTableSize" trigger="click">
					<Tooltip class="ivu-ml" content="密度" placement="top">
						<i-link>
							<Icon type="md-list" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
							<DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
							<DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
						</DropdownMenu>
					</template>
				</Dropdown>
				<Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
					<i-link @click="onFullscreen">
						<Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
					</i-link>
				</Tooltip>
				<Tooltip class="ivu-ml" content="刷新" placement="top">
					<i-link @click="onRefresh">
						<Icon custom="i-icon i-icon-refresh" />
					</i-link>
				</Tooltip>
				<Dropdown trigger="click">
					<Tooltip class="ivu-ml" content="列设置" placement="top">
						<i-link>
							<Icon type="md-options" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<div class="ivu-p-8">列展示</div>
							<Divider size="small" class="ivu-mt-8 ivu-mb-8" />
							<li class="ivu-dropdown-item" v-for="item in dropdownColumns" :key="item.title"
								@click="item.show = !item.show">
								<Checkbox v-model="item.show"></Checkbox>
								<span>{{ item.title }}</span>
							</li>
						</DropdownMenu>
					</template>
				</Dropdown>
			</div>
			<Table ref="table" :columns="tableColumns" :data="list" :loading="loading" :size="tableSize" class="ivu-mt"
				@on-selection-change="onCheckAlarmChange" @on-select-all="onCheckAlarmChange">
				<template #action="{ row }">
					<div @click.stop.prevent>
						<a style="color: #2d8cf0;" v-if="row.confirmStatus * 1 === 0" @click="onShowConfirm(row)">确认</a>
						<Poptip confirm title="您确定删除吗？" transfer @on-ok="onDelete(row)">
							<a style="color: #ed4014;" v-if="row.confirmStatus * 1 === 1">删除</a>
						</Poptip>
						<Divider type="vertical" />
						<a style="color: #ff9900;">查询工况</a>
					</div>
				</template>
			</Table>
			<div class="ivu-mt ivu-text-center">
				<Page :total="total" v-model="pageNum" show-total show-sizer show-elevator :page-size="pageSize"
					@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
			</div>
			</Col>
		</Row>
		<Modal title="确认" v-model="confirmVisible" @on-cancel="onCancel" :mask-closable="false">
			<Form ref="form" :model="confirmData" :rules="confirmRules">
				<Row :gutter="24" type="flex">
					<Col span="24">
					<FormItem label="确认原因" prop="reason" label-for="reason">
						<Input v-model="confirmData.reason" placeholder="请输入确认原因" element-id="reason" type="textarea" :rows="3" />
					</FormItem>
					</Col>
				</Row>
			</Form>
			<template #footer>
				<Button type="text" @click="onCancel">取消</Button>
				<Button type="primary" @click="onConfirm" :loading="loading">确定</Button>
			</template>
		</Modal>
	</div>
</template>
<script>
import DayJs from 'dayjs'
import { cloneDeep } from 'lodash'
import { getAreaList } from '@/api/common'
import { getAlarmMessage, updateAlarmMessage, deleteAlarmMessage, exportAlarmMessages } from '@api/alarm'

export default {
	data() {
		return {
			AlarmLevels: {
				1: '紧急',
				2: '严重',
				3: '警告',
				4: '消息',
			},
			AlarmTypes: {
				1: '数据异常',
				2: '状态异常',
			},
			loading: false,
			list: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			tableSize: 'small',
			tableFullscreen: false,
			allUsers: [],
			areaData: [],
			areaList: [],
			selectedArea: {},
			selectedAlarms: [],
			currentItem: {},
			confirmVisible: false,
			confirmData: {
				reason: ''
			},
			confirmRules: {
				reason: [
					{ required: true, message: '请输入确认原因' }
				],
			}
		}
	},
	computed: {
		columns() {
			return [
				{
					type: 'selection',
					width: 60,
					align: 'center'
				},
				{
					title: '告警等级',
					key: 'alarmLevel',
					render: (h, { row }) => {
						return h('span', this.AlarmLevels[row.alarmLevel])
					}
				},
				{
					title: '监控类型',
					key: 'alarmType',
					render: (h, { row }) => {
						return h('span', this.AlarmTypes[row.alarmLevel])
					}
				},
				{ title: '监控设备', key: 'deviceName' },
				{ title: '监控信号', key: 'signalName' },
				{ title: '告警内容', key: 'alarmContent' },
				{ title: '开始时间', key: 'startTime', width: 180 },
				{ title: '结束时间', key: 'endTime', width: 180 },
				{
					title: '状态',
					key: 'confirmStatus',
					render: (h, { row }) => {
						return h('span', row.confirmStatus * 1 === 1 ? '已确认' : '未确认')
					}
				},
				{ title: '确认人', key: 'confirmBy' },
				{ title: '确认原因', key: 'confirmReason' },
				{ title: '操作', key: 'action', slot: 'action', align: 'center', width: 140, fixed: 'right' }
			]
		},
		tableColumns() {
			const columns = [...this.columns];
			return columns
		},
		dropdownColumns() {
			return this.columns.filter(item => item.title)
		}
	},
	async mounted() {
		const response = await getAreaList({})
		this.areaData = response
		this.onGenerateTree(response)
	},
	methods: {
		async getData() {
			if (this.loading) return;
			this.loading = true;
			const params = this.$parent.$parent.$refs.form.data;
			const response = await getAlarmMessage({
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				deviceId: params.deviceId || undefined,
				signalId: params.signalId || undefined,
				alarmLevel: params.alarmLevel || undefined,
				confirmStatus: params.confirmStatus || undefined,
			})
			this.list = (response.records || []).map(item => ({
				...item,
				_disabled: this.selectedArea.nodeLevel !== 4
			}))
			this.total = response.total;
			this.loading = false;
		},
		onGenerateTree(areaList) {
			const treeData = areaList.filter(area => !area.parentId)
			for (let i = 0; i < treeData.length; i++) {
				treeData[i].expand = true
				treeData[i].children = []
				treeData[i].render = (h, { root, node, data }) => {
					return h('span', {}, data.nodeName)
				}
				cloneDeep(areaList).forEach(area => {
					if (area.parentId === treeData[i].nodeId) {
						if (!area.children) {
							area.expand = true
							area.children = []
							cloneDeep(areaList).forEach(subArea => {
								if (subArea.parentId === area.nodeId) {
									subArea.expand = true
									subArea.children = []
									cloneDeep(areaList).forEach(thirdArea => {
										if (thirdArea.parentId === subArea.id) {
											thirdArea.expand = true
											thirdArea.children = []
											thirdArea.render = (h, { root, node, data }) => {
												return h('span', {
													style: {
														width: '100%'
													}
												}, [
													h('span', {
														style: {
															display: 'inline-block',
															width: '80px',
														}
													}, data.nodeName),
												]);
											}
											subArea.children.push(thirdArea)
										}
									})
									subArea.render = (h, { root, node, data }) => {
										return h('span', {
											style: {
												width: '100%'
											}
										}, [
											h('span', {
												style: {
													display: 'inline-block',
													width: '80px',
												}
											}, data.nodeName),
										]);
									}
									area.children.push(subArea)
								}
							})
						}
						area.render = (h, { root, node, data }) => {
							return h('span', {
								style: {
									width: '100%'
								}
							}, [
								h('span', {
									style: {
										display: 'inline-block',
										width: '80px',
									}
								}, data.nodeName),
							]);
						}
						areaList[i].children.push(area)
					}
				})
			}
			this.areaList = treeData
		},
		onSelectChange(_, selectedArea) {
			this.selectedArea = selectedArea
			this.getData()
		},
		onChangeTableSize(size) {
			this.tableSize = size;
		},
		onFullscreen() {
			this.tableFullscreen = !this.tableFullscreen;
			this.$emit('on-fullscreen', this.tableFullscreen);
		},
		onRefresh() {
			this.getData();
		},
		onChangePage(page) {
			this.pageNum = page;
			this.getData();
		},
		onChangePageSize(size) {
			this.pageNum = 1;
			this.pageSize = size;
			this.getData();
		},
		onSearch() {
			this.pageNum = 1;
			this.getData();
		},
		onShowConfirm(row) {
			this.currentItem = row
			this.confirmVisible = true
			this.confirmData.reason = ''
		},
		onCancel() {
			this.currentItem = {}
			this.confirmVisible = false
			this.confirmData.reason = ''
		},
		async onConfirm() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					let params = {}
					if (this.currentItem.id) {
						params = {
							id: this.currentItem.id,
							confirmReason: this.confirmData.reason,
							confirmStatus: 1
						}
					}
					if (this.selectedAlarms.length) {
						params = this.selectedAlarms.filter(
							item => item.confirmStatus * 1 === 0
						).map(item => ({
							id: item.id,
							confirmReason: this.confirmData.reason,
							confirmStatus: 1
						}))
					}
					const response = await updateAlarmMessage(params)
					if (response.code === 1000) {
						this.$Message.success('确认成功')
						this.onRefresh()
						this.onCancel()
					}
				}
			})
		},
		async onDelete(row) {
			let params = {}
			if (row) {
				params = {
					id: row.id,
				}
			}
			if (this.selectedAlarms.length) {
				params = this.selectedAlarms.filter(
					item => item.confirmStatus * 1 === 1
				).map(item => item.id)
			}
			const response = await deleteAlarmMessage(params)
			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.pageNum = 1
				this.getData()
			}
		},
		onCheckAlarmChange(selection) {
			this.selectedAlarms = selection
		},
		async onShowBatchConfirm() {
			this.confirmVisible = true
			this.confirmData.reason = ''
		},
		exportCsv(csv, title) {
			const t = `${DayJs().format('YYYY-MM-DD')} ${Math.random().toString().slice(2, 8)}`
			const filename = `${t + ' ' + title}.xls`

			const blob = new Blob([csv], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
			})
			const url = window.URL.createObjectURL(blob)
			const downloadLink = document.createElement('a')
			downloadLink.href = url
			downloadLink.download = filename
			document.body.appendChild(downloadLink)
			downloadLink.click()
			document.body.removeChild(downloadLink)
			window.URL.revokeObjectURL(url)
		},
		async onExport() {
			const params = this.$parent.$parent.$refs.form.data;
			const response = await exportAlarmMessages({
				deviceId: params.deviceId || undefined,
				signalId: params.signalId || undefined,
				alarmLevel: params.alarmLevel || undefined,
				confirmStatus: params.confirmStatus || undefined,
			})
			this.exportCsv(response, '报警列表')
		}
	}
}
</script>
